package com.lineage.server.timecontroller.npc;

import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.WorldNpc;
import java.util.Collection;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NpcDeadTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(NpcDeadTimer.class);
  
  private static final int NpcDeadCount = 4;
  
  private static NpcDeadTimer _instance;
  
  private static ConsumRecycleNpcTask _task;
  
  private ScheduledFuture<?> _timer;
  
  public static NpcDeadTimer get() {
    if (_instance == null)
      _instance = new NpcDeadTimer(); 
    if (_task == null)
      _task = new ConsumRecycleNpcTask(); 
    return _instance;
  }
  
  public void start() {
    int timeMillis = 2000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 2000L, 2000L);
  }
  
  public void run() {
    try {
      Collection<L1NpcInstance> allMob = WorldNpc.get().all();
      if (allMob.isEmpty())
        return; 
      Stream<L1NpcInstance> stream = allMob.parallelStream();
      stream.forEach(_task);
    } catch (Exception e) {
      _log.error("NPC死亡移除时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      NpcDeadTimer npcDeadTimer = new NpcDeadTimer();
      npcDeadTimer.start();
    } 
  }
  
  public static class ConsumRecycleNpcTask implements Consumer<L1NpcInstance> {
    public void accept(L1NpcInstance npc) {
      try {
        if (npc == null)
          return; 
        if (npc.getMaxHp() <= 0)
          return; 
        if (!npc.isDead())
          return; 
        if (npc.get_deadTimerTemp() == -1)
          return; 
        int time = npc.get_deadTimerTemp() - 2;
        if (time < 0)
          time = 0; 
        npc.set_deadTimerTemp(time);
        if (npc.get_deadTimerTemp() <= 0)
          npc.deleteMe(); 
        Thread.sleep(4L);
      } catch (Exception e) {
        NpcDeadTimer._log.error("NPC死亡时间轴异常重启", e);
      } 
    }
  }
}
